﻿/// <reference path="CommentService.js" />
app.factory('CommentService', ['$http', '$q', '$location', function ($http, $q, $location) {
    var c = {
        comments: []
    };

    c.getComments = function () {
        var q = $q.defer();
        $http({
            url: '/api/apinote',
            method: 'GET',
            headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }
        }).success(function (data) {
            o.comments.length = 0;
            for (var i = 0; i < data.length; i++) {
                o.notes[i] = data[i];
            }
            $location.path('/usernoteIndex');
        }).error(function (data) {
        });
        return q.promise;
    };

    c.addComment = function (newComment) {
        $http({
            url: 'api/apinote',
            method: 'POST',
            headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
            data: newNote
        }).success(function (response) {
            //window.location.replace('/usernoteindex');
            //window.location.replace('#/UserNoteIndex');
            o.getNotes();
            $location.path("/UserNoteIndex");
        });
    };

    c.deleteComment = function (i) {
        $http({
            url: 'api/apinote/' + o.notes[i].Id,
            headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
            method: 'DELETE'
        }).success(function (response) {
            c.comments.splice(i, 1);
        }).error(function (response) {
            console.error(response);
        });
    };

    o.updateComment = function (i, editComment) {
        $http({
            url: 'api/apinote/' + o.notes[i].Id,
            headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
            method: 'PUT',
            data: editNote
        }).success(function (editComment, response) {
            c.getComments();
            $location.path("/UserNoteIndex");
        }).error(function (response) {
            console.error(response);
        });
    };

    return o;
}]);